import 'dart:async';

import 'package:aichat_flutter_wallet/module_common/utils/colors.dart';
import 'package:aichat_flutter_wallet/module_common/utils/util.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/button/public_button.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/nodeSpeed/nodeSpeed.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/public_tip/public_tip.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_database/lib_database.dart';

import 'package:lib_util/lib_util.dart';

import '../../../module_common/provider/wallet_info_provider.dart';
import '../../../module_common/widgets/blockies.dart';
import '../../../module_common/widgets/dialog/bottom_sheet_widget.dart';
import '../../../module_common/widgets/dialog/easyloading.dart';
import '../../../module_common/widgets/header/page_header.dart';
import 'package:flutter_slidable/flutter_slidable.dart';

import '../provider/wallet_node_provider.dart';
import '../widgets/row_delete_button.dart';
import '../widgets/assets_wallet_item.dart';
import '../widgets/noderow.dart';
import '../widgets/sheet/customnode_sheet.dart';

class WalletSetNode extends StatefulWidget {
  final Chain? chain;

  WalletSetNode({Key? key, this.chain});

  @override
  _WalletSetNodeState createState() => _WalletSetNodeState();
}

class _WalletSetNodeState extends State<WalletSetNode> {
  late Chain _chain;

  // List<NodeInfo>? _nodeList;
  late ValueNotifier<int> refreshRateNotifi;
  Timer? _timer;
  late int selectedRow;


  bool btnStatus=false;
  ScrollController scrollController = ScrollController();

  @override
  void initState() {
    super.initState();

    _chain = widget.chain ?? context.read<WalletInfoNotifier>().walletChain!;

    refreshRateNotifi = ValueNotifier<int>(1);
    selectedRow = 0;

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      context.read<NodeProvider>().updateNodePageList(chain: _chain.shortName);
    });
  }




  void startTimer() async {
    _timer = Timer.periodic(Duration(seconds: 5), (timer) {
      refreshRateNotifi.value = refreshRateNotifi.value + 1;
    });
  }

  @override
  void dispose() {
    refreshRateNotifi.dispose();
    if (_timer != null) {
      _timer!.cancel();
      _timer = null;
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: PageHeaderCom(
        title: String.fromEnvironment('emailString', defaultValue: "Node Management"),
        showBottomBorder: false,
      ),
      body: Container(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // SizedBox(height: 10),
            // walletWidget(),
            SizedBox(height: 20.w),
            speedDesc(),
            SizedBox(height: 20.w),
            nodeListView(),
            SizedBox(height: 10.w),
          ],
        ),
      ),
      bottomNavigationBar: bottomControl(),
    );
  }

  Widget titleWidget(String title) {
    return Text(title, style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.bold, color: "#333333".toColor()));
  }

  Widget walletWidget() {
    return Padding(
      padding: EdgeInsets.only(left: 20.w, right: 20.w),
      child: GestureDetector(
        onTap: () {
          //弹出选择钱包
          // Utils.showBottomSheetDialog(context, selectWalletSheet());
        },
        child: Container(
          decoration: BoxDecoration(
            border: Border.all(color: "#F6F6F6".toColor()),
            borderRadius: BorderRadius.circular(10.0.w),
          ),
          height: 50.w,
          child: Row(
            children: [
              SizedBox(width: 12.w),
              UserAvatar(
                walletId: 999 - context.read<WalletInfoNotifier>().walletId,
                size: 30.w,
              ),
              SizedBox(width: 10.w),
              Expanded(
                  child: Text(context.watch<WalletInfoNotifier>().walletName,
                      style: TextStyle(fontSize: 14.sp, fontWeight: FontWeight.bold, color: "#333333".toColor()))),
              // Image.asset(
              //   'assets/images/wallet/token_arrow.png',
              //   width: 12,
              //   height: 12,
              // ),
              SizedBox(width: 15.w),
            ],
          ),
        ),
      ),
    );
  }

  Widget speedDesc() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.only(left: 20.w, right: 20.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                'Node speed',
                style: TextStyle(fontSize: 12.sp, color: AppColors.c_333333, fontWeight: FontWeight.w400),
              ),
              // SizedBox(
              //   width: 20.w,
              // ),
              speedTips('Fast', NodeRateUtils.fastColor),
              // SizedBox(
              //   width: 20.w,
              // ),
              speedTips('Medium', NodeRateUtils.mediumColor),
              // SizedBox(
              //   width: 20.w,
              // ),
              speedTips('Slow', NodeRateUtils.slowColor),
              // SizedBox(
              //   width: 20.w,
              // ),
              speedTips('Error', NodeRateUtils.errorColor),
            ],
          ),
          SizedBox(height: 10.w),
          Text(
              'Block Height: This value indicates the latest data status and performance of a node. When nodes operate at similar speeds, selecting one with a higher block height ensures more prompt synchronization of wallet data.',
              style: TextStyle(fontSize: 12.sp, color: "#868391".toColor()))
        ],
      ),
    );
  }

  Widget speedTips(String text, Color color) {
    return Wrap(
      crossAxisAlignment: WrapCrossAlignment.center,
      runAlignment: WrapAlignment.start,
      children: [
        NodeSpeed(
          color: color,
          size: 16.w,
        ),
        SizedBox(width: 5.w),
        Text(text, style: TextStyle(fontSize: 10.sp, fontWeight: FontWeight.w400, color: "#333333".toColor()))
      ],
    );
  }

  Widget speedPoint(Color color) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(6.w),
      child: Container(
        width: 6.w,
        height: 6.w,
        color: color,
      ),
    );
  }

  Widget nodeListView() {
    return Expanded(
      child: SlidableAutoCloseBehavior(
        child: Consumer<NodeProvider>(// 使用 Consumer 来监听状态更改并重新构建此部分的 widget 树。
            builder: (context, provider, child) {
          var _nodeList = provider.nodeInfoList(chain: _chain.shortName);
          return ListView.separated(
              controller: scrollController,
              padding: EdgeInsets.only(right: 20.w),
              //因为左滑效果，所以这边加一个padding
              itemCount: _nodeList.length,
              separatorBuilder: (BuildContext context, int index) => //设置列表的间距
                  Divider(
                    height: 10.w,
                    color: Colors.white,
                  ),
              itemBuilder: (context, index) {
                return GestureDetector(
                  onTap: () async {
                    //更新数据库
                    if(this.btnStatus){
                      return;
                    }
                    this.btnStatus=true;
                    var selectNodeInfo = _nodeList[index];
                    final isSuccess= provider.selectNode(chain: _chain.shortName, selectedNode: selectNodeInfo);
                    EasyLoading.generateLoadingFuture(Future<bool?>.delayed(Duration(seconds: 2)));
                    if(isSuccess == false){
                      Toast.hide();
                      Toast.show(context, message: 'Updating the node, please select again later.',position: Dpositon.bottom,status: '-1',duration: const Duration(milliseconds: 2500));
                    }
                    this.btnStatus=false;
                    // final bool? isSuccess= ;
             
                  },
                  child: Slidable(
                      //创建一个可以侧滑的组件
                      enabled: !(_nodeList[index].isSelected || _nodeList[index].name == null),
                      key: Key(index.toString()),
                      child: NodeRow(
                          notifi: refreshRateNotifi, node: _nodeList[index], isSelected: _nodeList[index].isSelected , isLoading:provider.isLoading),
                      endActionPane: ActionPane(
                          //尾部组件
                          extentRatio: 0.2,
                          motion: ScrollMotion(),
                          children: [
                            Expanded(
                              child: SizedBox(),
                            ),
                            deleteButton(
                              onTap: (deleteCTX) {
                                provider.deleteNode(_nodeList[index]);
                                Slidable.of(deleteCTX)?.close();
                              },
                            )
                          ])),
                );
              });
        }),
      ),
    );
  }

  Widget bottomControl() {
    return Padding(
        padding: EdgeInsets.only(bottom: (MediaQuery.of(context).padding.bottom + 11).w),
        child: PublicButton(
          image: Image.asset(
            'assets/images/common/edit.png',
            height: 16.w,
            width: 16.w,
          ),
          text: 'Custom Node',
          onClick: () {
            Utils.showBottomSheetDialog(context, CustomNodeSheet());
          },
        ));
  }

  Widget textInputControl(
      {double? height,
      List<TextInputFormatter>? inputFormatters,
      int? maxLines = 1,
      String hintText = '',
      FocusNode? focusNode,
      TextEditingController? controller,
      TextInputAction? textInputAction,
      void Function()? onEditingComplete}) {
    return Container(
      height: height,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8.w),
        color: Color.fromRGBO(246, 246, 246, 1),
      ),
      child: Stack(
        children: [
          TextField(
              cursorHeight: 20.w,
              textInputAction: textInputAction,
              inputFormatters: inputFormatters,
              textAlign: TextAlign.justify,
              textAlignVertical: TextAlignVertical.top,
              controller: controller,
              focusNode: focusNode,
              onTapOutside: (PointDownEvent) {
                focusNode?.unfocus();
              },
              onEditingComplete: onEditingComplete,
              onChanged: (value) {
                // 当选项卡正在发生切换时触发的操作】
              },
              maxLines: maxLines,
              style: TextStyle(
                  color: Color.fromRGBO(51, 51, 51, 1), fontWeight: FontWeight.w400, fontSize: 14.sp, height: 20 / 14),
              decoration: InputDecoration(
                contentPadding: const EdgeInsets.all(15),
                border: InputBorder.none,
                hintText: hintText,
                hintStyle: TextStyle(
                  fontSize: 14.sp,
                  color: "#BEBDCA".toColor(),
                ),
              )),
        ],
      ),
    );
  }

  //选择钱包
  Widget selectWalletSheet() {
    List<Wallet> _walletList = ObjectBox().walletModel.getSortedWalletList();

    return BottomSheetWidget(
        title: 'Select Wallet',
        expand: false,
        child: Container(
          height: (404 + 50 + MediaQuery.of(context).padding.bottom).w,
          child: Column(
            children: [
              Expanded(
                  child: ListView.builder(
                itemCount: _walletList.length,
                itemBuilder: (context, index) {
                  return WalletListItem(wallet: _walletList[index], sortMode: false);
                },
              )),
            ],
          ),
        ));
  }
}
